<?php

namespace interface\v1;

use verify;

class loginAppClass extends index
{

    /**
     * 给个人用户设置默认设置
     */
    private function setDefaultSetting()
    {
        //生成OA小程序销售设置
        if (self::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = 'OA通知设置'")) == 0) {
            insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid'  => self::$stid,
                    'type'  => 'OA通知设置',
                    'value' => json_encode(['message' => 1], 320),
                ],
            ));
        }

        //判断是否有销售过程统计设置
        if (self::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = '销售过程统计'")) == 0) {
            insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid'  => self::$stid,
                    'type'  => '销售过程统计',
                    'value' => json_encode(["board", "follow_client", "sale_funnel", "follow_type", "follow_rank", "visit_rank"], 320),
                ],
            ));
        }
        //判断是否有销售业绩统计设置
        if (self::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = '销售业绩统计'")) == 0) {
            insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid'  => self::$stid,
                    'type'  => '销售业绩统计',
                    'value' => json_encode(["board", "performance_goals", "payment", "contract_money", "kpi_analysis", "losing_analysis", "sign_ranking", "goal_achievement"], 320),
                ],
            ));
        }
        //判断是否有客户分析设置
        if (self::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = '客户分析'")) == 0) {
            insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid'  => self::$stid,
                    'type'  => '客户分析',
                    'value' => json_encode(["geographical", "industry_scale", "status_funnel", "channel_analysis", "customer_add", "customer_ranking", "conversion_rate"], 320),
                ],
            ));
        }
    }

    /**
     * 获取userid
     *
     * @return void
     */
    public function getuserId()
    {
        $source = !empty($this->header['Source']) ? $this->header['Source'] : '';
        $code = $this->post('code');
        if ($source) {
            $source = strtolower($source);
        } else {
            $source = 'erp';
        }
        $token = static::getSuiteToken($source);
        if (empty($code)) {
            $this->resp['warn'] = '未找到code';
        } elseif (empty($token)) {
            $this->resp['warn'] = '未找到token,请检查参数配置';
        } else {
            $result = static::request([
                'url' => 'https://qyapi.weixin.qq.com/cgi-bin/service/miniprogram/jscode2session?suite_access_token=' . $token . '&js_code=' . $code . '&grant_type=authorization_code&debug=1',
            ], true);
            if ($result['errcode'] != 0) {
                $this->resp['warn'] = '获取userId失败' . json_encode($result, 320);
            } else {
                $user = query('user', " weChatUserId= '{$result['userid']}'");
                if (empty($user['uid'])) {
                    if (para('wechatMiniLoginLimit') == '是') {
                        $this->resp['warn'] = '登录失败，请在后台绑定企业微信ID';
                    } else {
                        //	写入游客信息
                        $stid = static::getId();
                        $name = 'Visitor_' . static::getId();
                        $userNo = 'YKID_' . strtoupper(substr(md5(uniqid()), 0, 14));
                        // 写入用户表
                        self::insert([
                            'table' => 'user',
                            'field' => [
                                'uid'          => self::getNo(),
                                'stid'         => $stid,
                                'userNo'       => $userNo,
                                'role'         => '["visitor"]', // 角色游客
                                'name'         => $name,
                                'userName'     => $name,
                                'password'     => md5s(para('staffPas')),
                                'operator'     => 'system',
                                'state'        => '启用',
                                'weChatUserId' => $result['userid'],
                                'time'         => $this->time,
                            ],
                        ]);
                        $orderNo = 'YKXX_' . strtoupper(substr(md5(uniqid()), 0, 14));
                        //	写入员工信息表
                        self::insert([
                            'table' => 'staff',
                            'field' => [
                                'stid'     => $stid,
                                'orderNo'  => $orderNo,
                                'name'     => $name,
                                'state'    => '转正',
                                'workFlow' => '已复核',
                                'ico'      => 'img/websiteImg/replaceHead.jpg',
                                'time'     => $this->time,
                            ],
                        ]);

                        // 返回数据
                        $this->code = 1;
                        $this->setDefaultSetting();
                        $token = md5s($stid);
                        (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                        $expireTime = 60 * 60 * $expireTime;
                        $this->rSet($token, $stid, $expireTime); // 设置redis
                        $this->resp['data']['token'] = $token;
                    }
                } else {
                    $logText = match ($source) {
                        'crm' => $user['name'] . '登录成功【CRM-小程序】-userId',
                        'erp' => $user['name'] . '登录成功【ERP-小程序】-userId',
                        default => $user['name'] . '登录成功【OA-小程序】-userId',
                    };
                    $this->code = 1;
                    $this->setDefaultSetting();
                    $token = md5s($user['stid']);
                    (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                    $expireTime = 60 * 60 * $expireTime;
                    $this->rSet($token, $user['stid'], $expireTime); // 设置redis
                    // 返回参数
                    unset($result['errcode'], $result['errmsg']);
                    $this->resp['data'] = $result;
                    $this->resp['data']['token'] = $token;
                    $this->logText(["type" => 'my', "text" => $logText], true);
                }
            }
        }
    }


    /**
     * 其他企业的人员访问本企业是产生加密userId
     */
    public function getUid()
    {
        $source = !empty($this->header['Source']) ? $this->header['Source'] : '';
        $code = $this->post('code');
        if ($source) {
            $source = strtolower($source);
        } else {
            $source = 'erp';
        }
        $token = static::getSuiteToken($source);
        if (empty($code)) {
            $this->resp['warn'] = '未找到code';
        } elseif (empty($token)) {
            $this->resp['warn'] = '未找到token';
        } else {
            $result = static::request([
                'url' => 'https://qyapi.weixin.qq.com/cgi-bin/service/miniprogram/jscode2session?suite_access_token=' . $token . '&js_code=' . $code . '&grant_type=authorization_code&debug=1',
            ], true);
            if ($result['errcode'] != 0) {
                $this->resp['warn'] = '获取userId失败' . json_encode($result, 320);
            } else {
                $this->code = 1;
                $this->resp['data']['uid'] = $result['userid'];
                $this->resp['data']['isLocal'] = 0;
                if ($result['corpid'] == para('qyWeChatCorpid')) {
                    $this->resp['data']['isLocal'] = 1;
                }
            }
        }
    }


    /**
     * 小程序登录(可通过openId转userId间接登录  https://developer.work.weixin.qq.com/document/path/90202)
     */
    public function weChatLogin()
    {
        $code = $this->post('code');
        $source = !empty($this->header['Source']) ? $this->header['Source'] : '';
        switch ($source) {
            case 'crm';
                $appid = para('wxCrmAppid');
                $secret = para('wxCrmAppSecret');
                break;
            case 'erp';
                $appid = para('wxErpAppid');
                $secret = para('wxErpAppSecret');
                break;
            default;//OA
                $appid = para('wxOaAppid');
                $secret = para('wxOaAppSecret');
                break;
        }
        $result = json_decode(self::curlGet("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code"), true);
        if (!isset($result['openid']) || empty($result['openid'])) {
            $this->resp['warn'] = $result['errmsg'];
        } else {
            $openid = $result['openid'];
            $token = match ($source) {
                'crm' => wechatToken('crmAccessToken'),
                'erp' => wechatToken('erpAccessToken'),
                default => wechatToken('oaAccessToken'),
            };
            if (empty($code)) {
                $this->resp['warn'] = '未找到code';
            } elseif (empty($token)) {
                $this->resp['warn'] = '未找到token';
            } else {
                $url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid?access_token={$token}";
                $result = json_decode(self::curlPost($url, json_encode(['openid' => $openid], 320), build: false), true);
                if ($result['errcode'] != 0) {
                    $this->resp['warn'] = $result['errmsg'];
                } else {
                    $user = query('user', " weChatUserId= '{$result['userid']}'");
                    if (empty($user['uid'])) {
                        $this->resp['warn'] = '登录失败，请在后台绑定企业微信ID';
                    } else {
                        $logText = match ($source) {
                            'crm' => $user['name'] . '登录成功【CRM-小程序】-微信端',
                            'erp' => $user['name'] . '登录成功【ERP-小程序】-微信端',
                            default => $user['name'] . '登录成功【OA-小程序】-微信端',
                        };
                        $this->code = 1;
                        $this->setDefaultSetting();
                        $token = md5s($user['stid']);
                        (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                        $expireTime = 60 * 60 * $expireTime;
                        $this->rSet($token, $user['stid'], $expireTime); // 设置redis
                        $this->resp['data']['token'] = $token;
                        $this->logText(["type" => 'my', "text" => $logText], true);
                    }
                }
            }
        }
    }

    /**
     * 小程序登录(可通过openId转userId间接登录  https://developer.work.weixin.qq.com/document/path/90202)
     */
    public function newWeChatLogin()
    {
        $code = $this->post('code');
        $iv = $this->post('iv');
        $encryptedData = $this->post('encryptedData');
        $source = !empty($this->header['Source']) ? $this->header['Source'] : '';
        switch ($source) {
            case 'client';
                $appid = para('wxClientAppid');
                $secret = para('wxClientAppSecret');
                break;
            default;//OA
                $appid = para('wxSupplierAppid');
                $secret = para('wxSupplierAppSecret');
                break;
        }
        //根据
        $result = json_decode(self::curlGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"), true);
        $token = $result['access_token'];
        if (empty($code)) {
            $this->resp['warn'] = '未找到code';
        } elseif (empty($token)) {
            $this->resp['warn'] = '未找到token';
        } else {
            $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
            $result = json_decode(self::curlPost($url, json_encode(["code" => $code], 320), build: false), true);
            if ($result['errcode'] != 0) {
                $this->resp['warn'] = $result['errmsg'];
            } else {
                $phone = $result['phone_info']['purePhoneNumber'];
                $aa_supplier_list = find(['table' => "aa_supplier_list", "where" => "phone = '$phone'"]);
                if ($aa_supplier_list['num'] > 0) {
                    $this->code = 1;
                    $logText = "供应商人员登录供应商小程序，手机号：$phone";
                    $this->logText(["type" => 'supplier', "text" => $logText], true);
                    $this->resp['data'] = [
                        'phone'=>$phone
                    ];
                } else {
                    $this->resp['warn'] = '未找到授权信息';
                }
            }
        }
    }

    public function login()
    {
        $token = $this->header['Auth'];
        $source = $this->header['Source'];
        if (!$token) {
            //走userId登录流程
            $this->resp['warn'] = '未找到token';
        } else {
            $stid = $token == -1 ? self::$stid : $this->rGet($token);
            if (!$stid) {
                $this->resp['warn'] = '登录凭证已过期，请重新登录';
            } else {
                $user = query('user', " stid = '$stid' ");
                if (!$user) {
                    $this->resp['warn'] = '未找到此用户';
                } else {
                    (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                    $expireTime = 60 * 60 * $expireTime;
                    $this->rSet($token, $user['stid'], $expireTime); // 设置redis
                    $this->resp['data'] = [
                        'token' => $token,
                    ];
                    $logText = match ($source) {
                        'crm' => $user['name'] . '登录成功【CRM-小程序】-token',
                        'erp' => $user['name'] . '登录成功【ERP-小程序】-token',
                        'pda', 'PDA' => $user['name'] . '登录成功【ERP-PDA】-token',
                        default => $user['name'] . '登录成功【OA-小程序】-token',
                    };
                    $this->code = 1;
                    $this->logText(["type" => 'my', "text" => $logText], true);
                }
            }
        }
    }

    /**
     * 账号密码登录
     */
    public function loginPWD()
    {
        $data = [
            'userName' => $this->post['userName'] ?? '',
            'password' => $this->post['password'] ?? '',
            'source'   => $this->post['source'] ?? '',
        ];
        // 注释
        $annotation = [
            'userName' => '用户名或手机号',
            'password' => '密码',
            'source'   => '来源',
            // 'deviceID'   => '设备ID',
        ];
        // 规则
        $rules = [
            'userName' => 'required',
            'password' => 'required|min_len:6,max_len:20',
            'source'   => 'required',
        ];
        // 校验是否符合规则
        $vt = new verify();
        $result = $vt->setAliases($annotation)->validate($data, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
        } else {
            $source = $data['source'];
            unset($data['source']);
            $user = query('user', " userName = '{$data['userName']}' ");
            if (self::isNull($user['uid']) || verifyPwd($data['password'], $user['password']) !== true) {
                $this->resp['warn'] = '登录失败，账号密码输入错误';
            } else {
                $token = md5s($user['stid']);
                (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                $expireTime = 60 * 60 * $expireTime;
                $this->rSet($token, $user['stid'], $expireTime); // 设置redis
                $this->resp['data'] = [
                    'token' => $token,
                ];
                $logText = match ($source) {
                    'crm' => $user['name'] . '登录成功【CRM小程序】-token',
                    'erp' => $user['name'] . '登录成功【ERP小程序】-token',
                    'pda', 'PDA' => $user['name'] . '登录成功【ERP-PDA】-userId',
                    default => $user['name'] . '登录成功【OA小程序】-token',
                };
                $this->code = 1;
                $this->logText(["type" => 'my', "text" => $logText], true);
            }
        }
    }


    public function checkBinding()
    {
        $batch = $this->post('batch');
        $aa_product = query("aa_product", "batch = '$batch'");
        $timeLong=para('unbindTime')??12;
        if (empty($aa_product['id'])) {
            $this->resp['warn'] = "系统中未找到发动机批次为 【{$batch}】的产品";
        } else if (!empty($aa_product['ai_iot_no'])) {
            $this->code = 1;;
            $this->resp['data'] = [
                "ai"     => $aa_product['ai_iot_no'],
//               "isShow" => date("Y-m-d", strtotime("+1 day", strtotime($aa_product['production_date']))) < $this->date ? "false" : "true"
                "isShow" =>strtotime(date('Y-m-d H:i:s')) -strtotime($aa_product['production_date'])<=(int)$timeLong * 3600 ? "false" : "true"
            ];
        } else {
            $this->code = 2;
            $this->resp['warn'] = "已绑定";

        }
    }

    public function bind()
    {
        $batch = $this->post('batch');
        $ai = $this->post('ai');
        $phone= $this->post('loginPhone')??'';
        $aa_product = query("aa_product", "batch = '$batch'");
        if (!empty($aa_product['ai_iot_no'])) {
            $this->resp['warn'] = "该发动机批次码已绑定AI智能码，请重新扫码";
        } else if (self::total(['table' => 'aa_product', "where" => " and ai_iot_no = '{$ai}' and id !='$aa_product[id]'"]) > 0) {
            $this->resp['warn'] = "该AI智能码已被绑定，请重新扫码";
        } else {
            $this->code = 1;
            update(['table' => "aa_product",
                    "where" => "id ='$aa_product[id]' ",
                    "field" => [
                        "ai_iot_no"       => $ai,
//                        "production_date" => $this->date,
                        "production_date" => date('Y-m-d H:i:s'),
                        "bind_state"      => 1
                    ]
            ]);
           insert(['table'=>'aa_bind_record',
                'field'=>[
                    'id'=>suiji('b'),
                    'phone'=>$phone,
                    'batch'=>$batch,
                    'ai_no'=>$ai,
                    'create_time'=>date('Y-m-d H:i:s'),
                    'bind_date'=>date('Y-m-d')
            ]]);
            $this->resp['data'] = [
                "batch" => $batch,
                "ai"    => $ai,
            ];

        }
    }

    public function unbind()
    {
        $batch = $this->post('batch');
        $ai = $this->post('ai');
        $aa_product = query("aa_product", "batch = '$batch' and ai_iot_no = '$ai'");
        if (empty($aa_product['id'])) {
            $this->resp['warn'] = "该AI智能码未与发动机批次码绑定，无需解绑";
        } else {
            $this->code = 1;
            update(['table' => "aa_product",
                    "where" => "id ='$aa_product[id]' ",
                    "field" => [
                        "ai_iot_no"       => "",
                        "production_date" => "",
                        "bind_state"      => 0
                    ]
            ]);
            $this->resp['warn'] = "解绑成功";
        }
    }

    public function getCodeInfo()
    {
        $code = $this->post('code')??'';
        if (!$code){
            $this->resp['warn'] = "参数不能为空";
            return [];
        }
        $type=$this->post('type')??1;
        $aa_product = query("aa_product", "ai_iot_no = '$code' or batch = '$code' ");
        if ($aa_product['id']) {
            $this->code = 1;
            $para = query("para", " paid ='showProductTime'");
            $this->resp['data'] = [
                "name"            => $aa_product['material_name'],
                "text"            => $aa_product['text'],
                "batch"            => $aa_product['batch'],
                "bind_state"      => $aa_product['bind_state'],
                "apply_state"     => $aa_product['apply_state'],
                "apply_date"      => $aa_product['apply_date'],
                "production_date" => $aa_product['production_date']?date('Y-m-d H:i:s',strtotime($aa_product['production_date'])):'',
                "isShowApply"     => $para['paValue'],
                "usageDays"       => $aa_product['apply_state'] == 1 ? $this->diffBetweenTwoDays($aa_product['apply_date'], $aa_product['production_date']) : "",
            ];
        } else {
            $this->resp['warn'] = "没有该产品，请重新扫码或搜索";
        }
    }

    /**
     * 求两个日期之间相差的天数
     * (针对1970年1月1日之后，求之前可以采用泰勒公式)
     * @param string $day1
     * @param string $day2
     * @return number
     */
    public function diffBetweenTwoDays($day1, $day2)
    {
        $second1 = strtotime($day1);
//        $second2 = strtotime($day2);
        $second2 = time();

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }

//        return ($second1 - $second2) / 86400 + 1;
        $date= ($second1 - $second2) / 86400;
        return intval($date);
    }

    public function setApplyDate()
    {
        $key = $this->post('key');
        $utc = $this->post('utc');
        $state = $this->post('state');
        $apply_state = 0;
        $info=query('aa_product',"ai_iot_no = '$key'");
        $sc=$info['production_date']??date('Y-m-d');
        $time=strtotime($sc)+12*60*60+$utc;
//        $time=strtotime($sc)+$utc;
       $utc=$time;
       $oldStatus=$info['apply_state'];
        if ($state == '41') {
            $apply_state = 1;
        }
        $data=[];
        if ($apply_state == 1) {
            self::update(['table' => "aa_product", "where" => "ai_iot_no = '$key'", "field" => ["utc"=> $this->post('utc')??'','updateTime'=>date('Y-m-d H:i:s'),"apply_date" => date("Y-m-d H:i:s", $utc), "apply_state" => $apply_state]]);
        $data['apply_date']=date("Y-m-d H:i:s", $utc);
        }else{
            $data['apply_date']=0;
        }
        if ($apply_state==1&&$oldStatus==0){

            $data['showT']=1;
        }else{
            $data['showT']=0;
        }
        $this->resp['data']=$data;
    }

    public function getBindRecord(){
        $phone=$phone= $this->post('loginPhone')??'';
        if (!$phone){
            $this->resp['warn'] = "参数缺失";
            return;
        }
        $dates=[];
        for($i=0;$i<7;$i++){
            $dates[]=date('Y-m-d',strtotime("-{$i} day"));
        }

        $where="phone = $phone and bind_date in ('".implode("','",$dates)."') order by create_time desc";
        $resData=find(['table'=>'aa_bind_record','where'=>$where]);
        $countNum=sqlNum('aa_bind_record', $where);
        $list=$resData['array'];
        $data=[];
        foreach ($dates as $d){
            $data[$d]=[];
        }
        foreach ($list as $v){
            $data[$v['bind_date']][]=$v;
        }
        $aa=[];
        foreach ($data as $key=> $d1){
            $aa[]=['time'=>$key,
                'data'=>$d1,

            ];
        }
        $this->code = 1;
        $this->resp['data'] = [
            'data'=>$aa,
            'count'=>$countNum
        ];
    }
}

